<script setup>

import Card from "@/components/Card.vue";
import {Message, Notebook, Refresh, Select, User} from "@element-plus/icons-vue";
import {useStore} from "@/store";
import {computed, reactive, ref} from "vue";
import {accessHeader, get, post} from "@/net";
import {ElMessage} from "element-plus";
import axios from "axios";

const store = useStore()

//处理注册时间
const registerTime = computed(()=>new Date(store.user.registerTime).toLocaleString())

//表单
const baseForm = reactive({
  username:'',
  gender:1,
  phone:'',
  qq:'',
  wx:'',
  desc:''
})

const emailForm = reactive({
  email:'',
  code:''
})

const desc = ref('')

//校验输入合法性
const baseFormRef = ref()
const emailFormRef = ref()
const validateUsername = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入用户名'))
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
    callback(new Error('用户名不能包含特殊字符，只能是中文/英文'))
  } else {
    callback()
  }
}
const rules = {
  username: [
    {validator: validateUsername, trigger: ['blur', 'change']},
    {min: 2, max: 10, message: '用户名的长度必须在2-10个字符之间', trigger: ['blur', 'change']},
  ], email: [
    {required: true, message: '请输入邮件地址', trigger: 'blur'},
    {type: 'email', message: '请输入合法的电子邮件地址', trigger: ['blur', 'change']}
  ]
}
//加载详细信息
get('/api/user/details', data => {
  baseForm.username = store.user.username
  baseForm.gender = data.gender
  baseForm.phone = data.phone
  baseForm.wx = data.wx
  baseForm.qq = data.qq
  baseForm.desc = desc.value = data.desc
  emailForm.email = store.user.email
  loading.form = false
})

//保存个人信息
const loading = reactive({
  form: true,
  base: false
})
function saveDetails() {
  baseFormRef.value.validate(isValid => {
    if (isValid) {
      loading.base = true
      post('/api/user/save-details', baseForm, () => {
        ElMessage.success('用户信息保存成功')
        //本地的用户名修改
        store.user.usernamew = baseForm.username
        desc.value = baseForm.desc
        loading.base = false
      }, (message) => {
        ElMessage.warning(message)
        loading.base = false
      })
    }
  })
}

//发送邮箱验证码
//计时器
const coldTime = ref(0)
const isEmailValid = ref(true)
const onValidate = (prop, isValid) => {
  if (prop === 'email')
    isEmailValid.value = isValid
}
function sendEmailCode() {
  emailFormRef.value.validate(isValid => {
    if (isValid) {
      coldTime.value = 60
      get(`/api/auth/ask-code?email=${emailForm.email}&type=modify`, () => {
        ElMessage.success(`验证码已成功发送到邮箱：${emailForm.email}，请注意查收`)
        //计时器启动
        const handle = setInterval(() => {
          coldTime.value--
          if (coldTime.value === 0) {
            clearInterval(handle)
          }
        }, 1000)
      }, (message) => {
        //失败处理
        ElMessage.warning(message)
        coldTime.value = 0
      })
    }
  })
}
//保存邮箱
function modifyEmail() {
  emailFormRef.value.validate(isValid => {
    if (isValid) {
      post('/api/user/modify-email', emailForm, () => {
        ElMessage.success('邮件修改成功')
        store.user.email = emailForm.email
        emailForm.code = ''
      })
    }
  })
}

//头像大小检查
function beforeAvatarUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error("头像只能是jpg/png")
    return false
  }else if(rawFile.size / 1024 > 100){
    ElMessage.error("头像大小不能大于100Kb")
    return false
  }else {
    return true
  }
}
//头像上传成功处理
function uploadSuccess(response){
  ElMessage.success("头像上传成功")
  store.user.avatar = response.data
}


</script>

<template>
  <div style="display: flex;max-width: 1000px;margin: auto">
    <div class="card-left">
      <Card :icon="User"
            title="账号信息设置"
            desc="请在这里设置您的个人信息">
        <el-form :model="baseForm" ref="baseFormRef" label-position="top" style="margin: 0 10px 10px 10px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="baseForm.username" maxlength="10"/>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="baseForm.gender">
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="baseForm.phone" maxlength="11"/>
          </el-form-item>
          <el-form-item label="qq号" prop="qq">
            <el-input v-model="baseForm.qq" maxlength="13"/>
          </el-form-item>
          <el-form-item label="微信号" prop="wx">
            <el-input v-model="baseForm.wx"/>
          </el-form-item>
          <el-form-item label="个人简介" prop="desc">
            <el-input type="textarea" rows="6" v-model="baseForm.desc" maxlength="500"/>
          </el-form-item>
          <el-button :icon="Select"
                     type="success"
                     @click="saveDetails"
                     :loading="loading.base">保存用户信息</el-button>

        </el-form>

      </Card>

      <Card style="margin-top: 10px"
            :icon="Message"
            title="电子邮件设置"
            desc="您可以在这里修改默认的电子邮件">
        <el-form :model="emailForm"
                 :rules="rules"
                 ref="emailFormRef"
                 @validate="onValidate"
                 label-position="top"
                 style="margin: 0 10px 10px 10px">
          <el-form-item label="电子邮件" prop="email">
            <el-input v-model="emailForm.email"/>
          </el-form-item>
          <el-form-item prop="code">
            <el-row style="width: 100%" :gutter="10">
              <el-col :span="18">
                <el-input v-model="emailForm.code" placeholder="请获取验证码"/>
              </el-col>
              <el-col :span="6">
                <el-button type="warning" style="width: 100%" :disabled="!isEmailValid || coldTime > 0"
                           @click="sendEmailCode" plain>
                  {{ coldTime > 0 ? `请稍后 ${coldTime} 秒` : '获取验证码' }}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-button :icon="Refresh" type="success" @click="modifyEmail">更新绑定邮箱</el-button>
        </el-form>
      </Card>
    </div>
    <div class="card-right">
<!--      右边固定不滚动-->
      <div style="position: sticky;top: 20px" >
        <Card>
          <div style="text-align: center;padding: 5px 15px 0 15px">
            <div>
              <el-avatar :size="70"
                         :src="store.avatarUrl"/>
              <div style="margin: 5px 0">
                <el-upload
                  :action="axios.defaults.baseURL+'/api/image/avatar'"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-success="uploadSuccess"
                  :headers="accessHeader()">
                  <el-button round size="small">修改头像</el-button>
                </el-upload>
              </div>
              <div style="font-weight: bold">
                  你好，{{store.user.username}}
              </div>

            </div>
            <el-divider style="margin:10px 0"/>
            <div style="font-size: 14px;color: gray;padding: 10px">
              {{desc || "这个用户很懒，什么都没有填写"}}
            </div>
          </div>
        </Card>
        <Card style="margin-top: 10px;font-size: 14px;text-align: center">
          <div>注册时间：{{registerTime}}</div>
          <div style="color: gray">欢迎走进Web3.0的世界！</div>
        </Card>
      </div>
    </div>

  </div>
</template>

<style scoped>
.card-left{
  flex: 1;
  margin: 20px;
}
.card-right{
  width: 300px;
  margin: 20px 30px 20px 0;
}

</style>